﻿using System;
using System.Collections.Generic;
using System.Linq;
using KPIS.GERP.SERVICE.DAL;
using KPIS.GERP.SERVICE.Model;

namespace KPIS.GERP.SERVICE.WorkflowService.Class
{
    public static class ApprovalTaskUtils
    {
        public static void UpdateRefTableRecordStatus(int refSeq, int refTypeSeq, string updateToRecordStatus,
                                                      int updateBy)
        {
            new ApprovalTaskDal().UpdateRecordStatusInRefTable(refSeq, refTypeSeq, updateToRecordStatus, updateBy);
        }

        public static approval_task CreateApprovalTask(string inTitle, string inConfirmAs, string approveAs,
            Guid instanceId, int inRequester, int inCreator, int inRefSeq, int inRefTypeSeq)
        {
            var newTask = new approval_task(inTitle, instanceId, inRequester, inCreator); 
            newTask.ApproveAs = approveAs;

            newTask.Reference = new ApprovalTaskDal().GetApprovalReference(inRefTypeSeq);
            newTask.Reference.ref_seq = inRefSeq;
            newTask.Reference.rule_approve_type_seq = inRefTypeSeq;
            newTask.RefSeq = inRefSeq;
            newTask.RefTypeSeq = inRefTypeSeq;

            newTask.AddHistoryHead("สร้างงานขออนุมัติใหม่", "", true);
            newTask.AddHistory("- หัวข้อ: <strong>'" + inTitle + "'</strong>", "", true);
            try
            {
                var ruleApproveDb = new RuleApprove();
                var ruleApproves = ruleApproveDb.GetRuleApprove(string.Empty,
                                                                Convert.ToString(inRefTypeSeq), true, true,
                                                                true, null, true).Where(o => o.rule_approve_type != null);
                var ruleApproveTypeName = (from r in ruleApproves select r.rule_approve_type.rule_approve_type_name).FirstOrDefault();

                newTask.AddHistory("- ประเภทคำขอ: '" + ruleApproveTypeName + "'", "", true);
            }
            catch (Exception ex)
            { 
            } 
            //newTask.AddHistory("- รหัส Unique ID = " + instanceId, "", false);
             // newTask.AddHistory("- เป็นคำขอของ = " + inRequester);

            return newTask;
        }

        public static void EndLoad(string errorMessage, ref approval_task task,
                                   TaskStatus newTaskStatus = TaskStatus.Failed)
        {
            task.Status = newTaskStatus;
            task.AddHistory(errorMessage);
            ApprovalStorageDb.UpdateOrAddIfNotExistApprovalTask(task);
            throw new Exception(errorMessage);
        }

        public static void LoadRequesterEmployee(ref approval_task newTask, int inRequester, int inCreator)
        {
            var employeeDal = new Employee();
            try
            {
                var employees = employeeDal.GetHrmPsEmployeeLite();

                newTask.RequestEmp = (from e in employees where e.emp_seq == inRequester select e).FirstOrDefault();
                newTask.CreatorEmp = (from e in employees where e.emp_seq == inCreator select e).FirstOrDefault();
                if (newTask.RequestEmp == null || newTask.RequestEmp.hrm_mp_positions == null)
                {
                    ApprovalTaskUtils.EndLoad(
                        string.Format("ไม่สามารถโหลดข้อมูลตำแหน่งของผู้ร้องขออนุมัติได้ (EmpSeq={0})", inRequester),
                        ref newTask);
                }
            }
            catch (Exception ex)
            {
                ApprovalTaskUtils.EndLoad(
                    string.Format("ไม่สามารถโหลดข้อมูลตำแหน่งของผู้ร้องขออนุมัติได้ (EmpSeq={0})", inRequester), ref newTask);
            } 
            newTask.AddHistory(string.Format("- ผู้ทำคำขอ: {0}", newTask.RequestEmp.full_name), "", true);
            newTask.AddHistory(string.Format("- สังกัดตามการบริหาร: {0}",
                                             (newTask.RequestEmp.hrm_mp_job_sites != null
                                                  ? newTask.RequestEmp.hrm_mp_job_sites.job_site_name
                                                  : "")), "", true);
            newTask.AddHistory(string.Format("- ตำแหน่ง: {1}", newTask.RequestEmp.hrm_mp_positions.pos_ref,
                                             newTask.RequestEmp.hrm_mp_positions.pos_name), "", true);
        }

        public static void LoadRuleApproveFromType(ref approval_task newTask, int? ruleApproveTypeSeq)
        {
            var dalEmployee = new Employee();
            var positions = dalEmployee.GetHrmMpPositions(null, null, null, null, null, null, null, null, false,
                                                             false, false, true, false, true);
            var employees = dalEmployee.GetHrmPsEmployeeLite(null);
            try
            {
                var ruleApproveDb = new RuleApprove();
                newTask.RuleApproves = ruleApproveDb.GetRuleApprove(string.Empty,
                                                                    Convert.ToString(ruleApproveTypeSeq), true, true,
                                                                    true, null, true);
            }
            catch (Exception ex)
            {
                ApprovalTaskUtils.EndLoad(
                    string.Format("ไม่สามารถโหลดกฎการอนุมัติได้, รหัสประเภทกฎการอนุมัติที่โหลด={0}", ruleApproveTypeSeq),
                    ref newTask);
            } 
            newTask.AddHistory(string.Format("ใช้เป็นวิธีอนุมัติ <span>'{1}'</span> มีขั้นตอนอนุมัติ {0} ขั้นตอน",
                                             newTask.RuleApproves.Count, newTask.FirstRuleApproveTypeName));
            var lastEmpSeq = 0;
            foreach (var ruleApprove in newTask.RuleApproves)
            {
                var stepNumber = ruleApprove.step;
                var approverTypeName = ruleApprove.approver_type_name;
                var approverIs = "";
                var actionOption = ApprovalUtil.ConvertShortActionToWord(ruleApprove.action);
                actionOption = string.IsNullOrWhiteSpace(actionOption)
                                   ? ""
                                   : string.Format(" โดยมีสิทธิ์ <span style='color:blue'>{0}</span>", actionOption);
                if (ruleApprove.rule_approve_type_seq == 1)
                {
                    var approverSeq = ruleApprove.approver_seq;
                    var approverPosition = (from position in positions
                                            where position.pos_seq == approverSeq
                                            select position).FirstOrDefault();
                    if (approverPosition != null)
                    {
                        approverIs += approverPosition.pos_name;
                        
                        var approverEmployee = (from employee in employees
                                                where employee.pos_seq == approverPosition.pos_seq
                                                select employee).FirstOrDefault();

                        approverIs += approverEmployee != null
                                          ? " ผู้ดำรงค์ตำแหน่งปัจจุบัน คือ " + approverEmployee.full_name
                                          : " (ไม่มีผู้ดำรงค์ตำแหน่ง)";

                        lastEmpSeq = approverEmployee != null ? approverEmployee.emp_seq : 0;
                    }
                }
                //else if (ruleApprove.rule_approve_type_seq == 5)
                //{
                //    var posHead = dalEmployee.LoadJobSiteHeadEmployee(newTask.CurrentStep.)
                //    var approverEmployee = (from employee in employees
                //                            where employee.pos_seq == approverPosition.pos_seq
                //                            select employee).FirstOrDefault();

                //    approverIs += approverEmployee != null
                //                      ? " ผู้ดำรงค์ตำแหน่งปัจจุบัน คือ " + approverEmployee.full_name
                //                      : " (ไม่มีผู้ดำรงค์ตำแหน่ง)";
                //}
                newTask.AddHistory(string.Format("- {0} อนุมัติโดย{1}{2}{3}", stepNumber, approverTypeName, approverIs, actionOption));
            }

            if (newTask.RuleApproves.Count == 0)
                ApprovalTaskUtils.EndLoad("คำขอประเภทนี้ไม่ได้ทำการกำหนดกฎวิธีการอนุมัติใดๆ ไว้", ref newTask);
        }

        public static hrm_ps_employees GetLastEmp(ref approval_task approvalTask, int actionByEmpSeq)
        {
            int lastEmpSeq = (approvalTask.CurrentStep == 0
                                  ? approvalTask.RequestEmpSeq
                                  : actionByEmpSeq);
            return (new Employee().GetHrmPsEmployeeLite(new hrm_ps_employees {emp_seq = lastEmpSeq})).FirstOrDefault();
        }
        
        public static void UpdateRefRecordStatus(ref approval_task approvalTask, int actionByEmpSeq)
        {
            string newRecordStatus = approvalTask.RefTableStatus;
            int approvalTaskSeq = approvalTask.ApprovalTaskSeq;
            if(approvalTask.Reference == null)
                return;

            int refSeq = approvalTask.Reference.ref_seq;
            int refTypeSeq = approvalTask.Reference.rule_approve_type_seq;

            if (!string.IsNullOrWhiteSpace(newRecordStatus) && approvalTaskSeq != 0)
            {
                ApprovalTaskUtils.UpdateRefTableRecordStatus(refSeq, refTypeSeq, newRecordStatus, actionByEmpSeq);
            }
            //else if()
            //{
            //    approvalTask.AddHistory(string.Format("มีปัญหาในการปรับปรุงข้อมูลอ้างอิง info:{0},{1},{2},{3}", refSeq, refTypeSeq, newRecordStatus, actionByEmpSeq));
            //}

            if (approvalTask.Completed)
            {
                approvalTask.CurrentRuleApprove = null;
            }
        }

        public static void CheckApprovalUpper(ref approval_task approvalTask, bool isHeIsTop)
        {
            if (isHeIsTop)
            {
                // approvalTask.AddHistory("ผู้ขอหรือส่งต่อคำขออนุมัติในขั้นตอนนี้ ไม่มีผู้บังคับบัญชาที่เหนือกว่า");
                try
                {

                    approvalTask.CurrentRuleApprove.Approvers = RuleApproveDb.GetApprovers(
                        approvalTask.CurrentRuleApprove.
                            rule_approve_seq,
                        approvalTask.LastActionData.By.pos_seq.Value,
                        out isHeIsTop);
                }
                catch (Exception ex)
                {
                    approvalTask.AddHistory("เกิดปัญหาระหว่างการโหลดข้อมูลผู้อนุมัติคนต่อไป");
                }
            }
        }

        public static List<int> CaseComplete(ref approval_task approvalTask, hrm_ps_employees actionByEmp)
        {
            var result = new List<int>();
            if (approvalTask.Completed)
            {
                try
                {
                    var reference = approvalTask.Reference.ref_seq;
                    var taskStatus = approvalTask.Status;
                    var userWhoDone = actionByEmp.full_name;
                    result.AddRange(ApproveDataLoader.SendMessage(approvalTask,
                                                                  string.Format(
                                                                      "คำขออนุมัติหมายเลข {0} ของท่านได้รับการปรับเป็นสถานะ {1} โดย {2}",
                                                                      reference,
                                                                      taskStatus,
                                                                      userWhoDone), approvalTask.RequestEmp, ""));
                    approvalTask.AddHistory(string.Format("สิ้นสุดคำขอ", approvalTask.RuleApproves.Count));
                    approvalTask.CurrentStep = approvalTask.RuleApproves.Count;
                    approvalTask.CurrentRuleApprove = null;
                }
                catch (Exception ex)
                {

                }
            }
            return result;
        }
         
    }
}